<template>
  <div class="blog-paginate">
    <!-- 首页按钮 -->
    <button
        class="paginate-button"
        :class="{ disabled: currentPage === 1 }"
        @click="goToFirstPage"
    >
      首页
    </button>

    <!-- 上一页按钮 -->
    <button
        class="paginate-button"
        :class="{ disabled: currentPage === 1 }"
        @click="goToPrevPage"
    >
      上一页
    </button>

    <!-- 分页数字按钮 -->
    <button
        v-for="page in visiblePages"
        :key="page"
        class="paginate-button"
        :class="{ active: currentPage === page }"
        @click="goToPage(page)"
    >
      {{ page }}
    </button>

    <!-- 下一页按钮 -->
    <button
        class="paginate-button"
        :class="{ disabled: currentPage === totalPages }"
        @click="goToNextPage"
    >
      下一页
    </button>

    <!-- 末页按钮 -->
    <button
        class="paginate-button"
        :class="{ disabled: currentPage === totalPages }"
        @click="goToLastPage"
    >
      末页
    </button>
  </div>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
  totalItems: {
    type: Number,
    required: true,
  },
  itemsPerPage: {
    type: Number,
    default: 10,
  },
  currentPage: {
    type: Number,
    required: true,
  },
});

const emit = defineEmits(['page-change']);

// 计算总页数
const totalPages = computed(() => Math.ceil(props.totalItems / props.itemsPerPage));

// 计算可见的页码范围（当前页前后各显示2页）
const visiblePages = computed(() => {
  const pages = [];
  const startPage = Math.max(1, props.currentPage - 2);
  const endPage = Math.min(totalPages.value, props.currentPage + 2);

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }

  return pages;
});

// 跳转到指定页码
const goToPage = (page) => {
  if (page !== props.currentPage) {
    emit('page-change', page);
  }
};

// 跳转到首页
const goToFirstPage = () => goToPage(1);

// 跳转到上一页
const goToPrevPage = () => goToPage(props.currentPage - 1);

// 跳转到下一页
const goToNextPage = () => goToPage(props.currentPage + 1);

// 跳转到末页
const goToLastPage = () => goToPage(totalPages.value);
</script>

<style scoped>
.blog-paginate {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 20px;
}

.paginate-button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
  color: #333;
  cursor: pointer;
  transition:
      background-color 0.3s,
      color 0.3s,
      border-color 0.3s;
}

.paginate-button:hover:not(.disabled) {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.paginate-button.active {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.paginate-button.disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>